<!--
/// 
/// MaDAson - Toolkit for Model Driven Software Development
///
/// Copyright [2006] Marcus Lankenau
/// 
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///  
///     http://www.apache.org/licenses/LICENSE-2.0
///  
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
/// 
-->
<%@ Page Language="C#" %>
<%@ Import Namespace="Madason.MetaModel" %>
<%@ Import Namespace="Madason.MetaModel.DAO" %>

<% foreach (Entity cls in Model.DeepGetClasses().Filter(Stereotype.Entity)) { %>
<%   if (cls.Stereotype == Stereotype.Entity) { %>

/**
	<%= cls.Documentation %>
*/
CREATE TABLE [<%= cls.TableName %>]
(
	<%
		System.Collections.Generic.List<string> defs = new System.Collections.Generic.List<string>();
	%>
	<% foreach(PersistedAttribute attr in AllAttributes(cls)) { %>
	<%   if (attr.Stereotype == Stereotype.Transient) continue; %>
	<%   defs.Add(attr.ColumnName + " " + attr.ColumnType + (attr.Stereotype == Stereotype.PrimaryKey ? " NOT NULL PRIMARY KEY IDENTITY" : "")); %>	
	<% } %>	
	<% foreach (PersistedAssociation assoc in cls.ActiveAssociations) { %>
	<%   defs.Add(assoc.ColumnName + " int"); %>
	<% } %>
	<% foreach (StateMachine sm in cls.StateMachines) { %>
	<%   defs.Add(sm.Name + " int"); %>
	<% } %>
	
	<% for (int i=0; i<defs.Count; i++) { %>
	<%= defs[i] + ((i<defs.Count-1) ? "," : "") %>
	
	<% } %>   
)

<%   } %>
<% } %>

<% foreach (Entity cls in Model.DeepGetClasses().Filter(Stereotype.Entity)) { %>
<%   if (cls.Stereotype == Stereotype.Entity) { %>
<%     foreach(PersistedAssociation assoc in cls.ActiveAssociations) {  %>

ALTER TABLE [<%= cls.TableName %>] ADD CONSTRAINT [FK_<%= cls.Name %>_<%= assoc.ColumnNameClean %>] 
	FOREIGN KEY (<%= assoc.ColumnName %>) 
	REFERENCES [<%= (assoc.TargetClass as Entity).TableName %>] (<%= (assoc.TargetClass.Attributes.FindOneByStereotype(Stereotype.PrimaryKey) as PersistedAttribute).ColumnName %>);
<%	   } %>
<%   } %>
<% } %>

<script runat="server">
	private Model @model;
	
	public AttributeList AllAttributes(Entity cls)
	{
		AttributeList list = new AttributeList();
		
		if (cls.SuperClass != null) list.Add(cls.PrimaryKey);
		list.AddRange(cls.Attributes);
		return list;
	}

	
	public Model Model
	{
		get { return model; }
		set { model = value; }
	}

	public Madason.MetaModel.Attribute GetPrimaryKey(Entity cls)
	{
		return cls.PrimaryKey;
	}	
	
</script>